package com.example.yichuangyun.mvvm.ui.activity.order;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityPlaceOrderBinding;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.dialog.TreeDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.order.CreateOrderReqModel;
import com.example.yichuangyun.model.order.SelectOrderInfoDataModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.view.PlaceOrderViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.PlaceOrderAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.treelist.Node;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 下单
 */
@SuppressLint("NotifyDataSetChanged")
public class PlaceOrderActivity extends BaseActivity<ActivityPlaceOrderBinding, PlaceOrderViewModel> {

    private PlaceOrderAdapter placeOrderAdapter;
    private SelectOrderInfoDataModel selectOrderInfoDataModel;
    private List<SelectOrderInfoDataModel.OrderProductModel> productList;
    private String signUserId;
    private DecimalFormat decimalFormat;
    private boolean isFirstReq = true;
    private double totalPrice = 0;
    private TreeDialog treeDialog;
    private final List<Node> mTreeData = new ArrayList<>();
    private String mKeyword = "";
    private Node chooseNode;
    private SinglePickerView singlePickerView;
    private final List<String> orderTypeData = new ArrayList<>();
    private TimePicker timePicker;

    @Override
    protected PlaceOrderViewModel bindModel() {
        return getViewModel(this, PlaceOrderViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.create_order));
        decimalFormat = new DecimalFormat("0.00");
        placeOrderAdapter = new PlaceOrderAdapter(context);
        binding.recyclerView.setAdapter(placeOrderAdapter);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String id = bundle.getString(Constant.idKey);
            showLoadingDialog();
            viewModel.selectOrderInfo(id, context);
        }
        orderTypeData.add(getString(R.string.yu_order_text));
        orderTypeData.add(getString(R.string.offline_order));
        initDialog();
        viewModel.getTreeList("");
    }

    @Override
    protected void initClick() {
        viewModel.orderInfoDataModelMutableLiveData.observe(this, selectOrderInfoDataModel -> {
            this.selectOrderInfoDataModel = selectOrderInfoDataModel;
            signUserId = selectOrderInfoDataModel.getSignUserId();
            binding.tvSignPerson.setText(CommonUtil.checkText(selectOrderInfoDataModel.getSignName()));
            binding.tvCompanyName.setText(!TextUtils.isEmpty(selectOrderInfoDataModel.getCompanyName())
                    ? getString(R.string.place_order_company_info, selectOrderInfoDataModel.getCompanyName(),
                    getString(selectOrderInfoDataModel.getStatus() == 1 ? R.string.established : R.string.to_be_established)) : "");
            binding.setMOrderInfoDataModel(selectOrderInfoDataModel);
        });
        viewModel.productListMutableLiveData.observe(this, orderProductModels -> {
//            Log.e("@@@@@@#", new Gson().toJson(orderProductModels));
            productList = orderProductModels;
            totalPrice = 0;
            boolean isNoPrice = false;
            for (SelectOrderInfoDataModel.OrderProductModel orderProductModel : orderProductModels) {
                if (orderProductModel.getPrice() == -1) {
                    isNoPrice = true;
                    break;
                }
                totalPrice += orderProductModel.getPrice();
            }
            binding.tvTotalPrice.setText(isNoPrice ? getString(R.string.no_price) : getString(R.string.total_price, totalPrice == 0 ? String.valueOf(0) : decimalFormat.format(totalPrice)));
            binding.tvCreateOrder.setText(getString(isNoPrice ? R.string.no_price : R.string.commit_order));
            binding.tvCreateOrder.setBackgroundResource(isNoPrice ? R.drawable.shape_button_def : R.drawable.shape_button_sel);
            binding.tvCreateOrder.setEnabled(!isNoPrice);
            if (isFirstReq) {
                placeOrderAdapter.submitList(orderProductModels);
            } else {
                placeOrderAdapter.notifyDataSetChanged();
            }
            dismissLoadingDialog();
        });

        placeOrderAdapter.setAttrListener(reqModel -> {
            isFirstReq = false;
            viewModel.getPrice(reqModel);
        });

        viewModel.onDelayClick(binding.tvCreateOrder, o -> {
            UMengUtil.setCountEventId(Constant.CREATE_ORDER);
            showLoadingDialog();
            if (selectOrderInfoDataModel != null && productList != null) {
                CreateOrderReqModel createOrderReqModel = new CreateOrderReqModel();
                createOrderReqModel.setBusinessId(selectOrderInfoDataModel.getId());
                createOrderReqModel.setOrderType(binding.tvOrderType.getText().toString().equals(getString(R.string.offline_order)) ? 2 : 1);
                createOrderReqModel.setProductTotalPrice(totalPrice);
                createOrderReqModel.setSumPrice(totalPrice);
                createOrderReqModel.setSignDate(binding.tvSignTime.getText().toString());
                createOrderReqModel.setSignUserId(signUserId);

                List<CreateOrderReqModel.ProductListReqModel> productReqList = new ArrayList<>();
                for (SelectOrderInfoDataModel.OrderProductModel productModel : productList) {
                    CreateOrderReqModel.ProductListReqModel productListReqModel = new CreateOrderReqModel.ProductListReqModel(productModel.getId(), productModel.getPrice(), productModel.getPrice());
                    productReqList.add(productListReqModel);
                    List<CreateOrderReqModel.ServiceReqModel> serviceReqList = new ArrayList<>();
                    for (SelectOrderInfoDataModel.OrderServiceModel serviceModel : productModel.getServiceList()) {
                        CreateOrderReqModel.ServiceReqModel serviceReqModel = new CreateOrderReqModel.ServiceReqModel(serviceModel.getServiceName(), serviceModel.getId(), serviceModel.getServiceCostId());
                        serviceReqList.add(serviceReqModel);
                        List<CreateOrderReqModel.AttrReqModel> attrReqList = new ArrayList<>();

                        for (SelectOrderInfoDataModel.OrderAttrsModel attrsModel : serviceModel.getAttrs()) {
                            for (SelectOrderInfoDataModel.OrderMsgModel msgModel : attrsModel.getMsgs()) {
                                if (msgModel.isSelect()) {
                                    if (attrsModel.getAttName().equals(getString(R.string.service_period))) {
                                        serviceReqModel.setServiceCycle(msgModel.getAttrMsg());
//                                        serviceReqModel.setServicePeriod(serviceModel.getServicePeriod());
                                    } else {
                                        CreateOrderReqModel.AttrReqModel attrReqModel = new CreateOrderReqModel.AttrReqModel(msgModel.getAttrMsg(), msgModel.getPrice());
                                        attrReqList.add(attrReqModel);
                                    }
                                }
                            }
                        }
                        serviceReqModel.setAttrsName(attrReqList);
                    }
                    productListReqModel.setServiceList(serviceReqList);
                }
                createOrderReqModel.setProductList(productReqList);

                Log.e("@@@@@@@@生成订单", new Gson().toJson(createOrderReqModel));
                viewModel.createOrder(createOrderReqModel);
            }
        });

        viewModel.createOrderSuccessMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            EventBus.getDefault().post(new EventBusModel(Constant.closeOrderDetails));
            JumpIntent.jump(this, OrderResultActivity.class, true);
        });

        viewModel.mErrorData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });

        viewModel.treeData.observe(this, setShareBean -> {
            dismissLoadingDialog();
            if (setShareBean.getData() != null) {
                Node node = setShareBean.getData();
                mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                initList(node.getChildren());
                initList(node.getUserList());
                if (chooseNode != null) {
                    for (Node mNode : mTreeData) {
                        if (mNode.getId().equals(chooseNode.getId())) {
                            mNode.setChecked(true);
                            break;
                        }
                    }
                }
            }
            treeDialog.refreshData(TextUtils.isEmpty(mKeyword) ? 1 : 10);
        });

        viewModel.onDelayClick(binding.rlSignOrderTime, o -> timePicker.showPickerView());
        viewModel.onDelayClick(binding.rlOrderType, o -> singlePickerView.showSinglePickerView());
        viewModel.onDelayClick(binding.rlSignOrderPerson, o -> treeDialog.showDialog());
    }

    private void initDialog() {
        treeDialog = new TreeDialog(this, mTreeData, true) {

            @Override
            public void confirm(Node node) {
                chooseNode = node;
                binding.tvSignPerson.setText(chooseNode.getName());
                signUserId = chooseNode.getOrgId();
            }

            @Override
            public void search(String keyword, Node node) {
                showLoadingDialog();
                mKeyword = keyword;
                viewModel.getTreeList(keyword);
            }
        };

        treeDialog.reset();
        treeDialog.setFlag(1);
        treeDialog.setTitle(getString(R.string.please_choose_sign_person));

        singlePickerView = new SinglePickerView(this, getString(R.string.order_type_text), orderTypeData) {
            @Override
            public void confirm(String label, int position) {
                binding.tvOrderType.setText(label);
            }
        };

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.add(Calendar.DATE, -29);
        endDate.add(Calendar.YEAR, 10);
        timePicker = new TimePicker(this, startDate, endDate) {
            @Override
            public void confirm(String date) {
                binding.tvSignTime.setText(date);
            }
        };
    }

    private void initList(List<Node> list) {
        if (list == null || list.size() == 0)
            return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            if (node.getIsLeave() != 1) {
                mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId(), node.getIsLeave()));
            }
            if (node.getChildren() == null || node.getChildren().size() == 0) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }
}